import { useState, useEffect } from 'react'

const toString = Object.prototype.toString
/**
 * 获取window滚动距离
 */
export function useWindosScroll() {
  const [y, setY] = useState(0)

  useEffect(() => {
    const scrollHandler = () => {
      const h = document.documentElement.scrollTop
      setY(h)
    }
    window.addEventListener('scroll', scrollHandler)
    return () => window.removeEventListener('scroll', scrollHandler)
  })
  return [y]
}

export function useLocalStorage(key, defaultValue = null) {
  const [value, setValue] = useState(() => {
    let oldValue = localStorage.getItem(key)
    if (oldValue === null) return defaultValue
    try {
      return JSON.parse(oldValue)
    } catch (error) {
      return defaultValue
    }
  })
  useEffect(() => {
    localStorage.setItem(key, JSON.stringify(value))
  }, [value])
  return [value, setValue]
}
